package com.zbw.weightlibrary.Activity;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.zbw.weightlibrary.Connector.IBleControl;
import com.zbw.weightlibrary.Connector.IinfoCallback;
import com.zbw.weightlibrary.Connector.NewWeight;
import com.zbw.weightlibrary.Connector.WeightData;
import com.zbw.weightlibrary.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者 ：jae
 * 时间 ：2019-02-26 11:31
 * 这个类是干嘛的？：麟罗蓝牙电子称测试界面
 */
public class BleConnectActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener, IinfoCallback {
    /**
     * 手机蓝牙适配器
     */
    private BluetoothAdapter mBluetoothAdapter;

    /**
     * 称重重量显示控件
     */
    private TextView mTvWeight;
    private Button ButTest, ButBreak, ButComfirm;
    private Button ButGetWeight;
    private TextView textTitle;
    private TextView tvTitle;
    private ListView listView1;
    private ProgressBar progress_bar;
    private UserAdapter mPairedDevicesAdapter;
    private List<BTDevice> devices;
    private String Address;
    private RelativeLayout rela_layout;
    private IBleControl IControl;
    private String BTName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_linluo_ble);
        setActivitySize(0.5, 0.6);//Activity大小
        // 隐藏系统通知栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //控件初始化
        initUI();
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //判断手机是否有蓝牙
        if (mBluetoothAdapter==null) {
            Toast.makeText(this, "设备上没有蓝牙，退出", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        //注册设备发现广播接收器
        registerDeviceFoundReceiver(mDeviceFoundReceiver, this);
    }


    /**
     * 动态设置Activity的大小。
     */
    protected void setActivitySize(double width,double height) {
        //动态设置Activity的大小。
        Display display = getWindowManager().getDefaultDisplay(); // 为获取屏幕宽、高
        Point point = new Point();
        display.getSize(point);
        Window window = getWindow();
        WindowManager.LayoutParams windowLayoutParams = window.getAttributes(); // 获取对话框当前的参数值
        windowLayoutParams.width = (int) (point.x * width); // 宽度设置为屏幕的0.7
        windowLayoutParams.height = (int) (point.y * height); // 高度设置为屏幕的0.7
        windowLayoutParams.alpha = 1f;// 设置透明度
        getWindow().setAttributes(windowLayoutParams);
        //弹框式Activity设置圆角，注意：下面代码的顺序不可以改变，否则圆角效果设置不起效
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        View view = getWindow().getDecorView();
        view.setBackgroundResource(R.drawable.activiy_corners_white);//圆角背景
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if (!mBluetoothAdapter.isEnabled()) {
            Toast.makeText(this, "请先打开蓝牙", Toast.LENGTH_SHORT).show();
        }
        //检查定位权限是否已经开启
        if (!isLocationPermissionEnabled(this)) {
            requestLocationPermission(this);
        }
        //开始扫描设备
        startDiscoveryDevice();
    }

    private void initUI() {
        mTvWeight = (TextView) findViewById(R.id.tv_weight);
        mPairedDevicesAdapter = new UserAdapter(this, R.layout.weight_device_name);
        ButBreak = (Button) findViewById(R.id.ButBreak);
        ButBreak.setOnClickListener(this);
        ButTest = (Button) findViewById(R.id.ButTest);
        ButTest.setOnClickListener(this);

        ButComfirm = (Button) findViewById(R.id.ButComfirm);
        ButComfirm.setOnClickListener(this);
        rela_layout = (RelativeLayout) findViewById(R.id.rela_back);
        rela_layout.setOnClickListener(this);
        textTitle = (TextView) findViewById(R.id.textTitle);
        listView1 = (ListView) findViewById(R.id.listView1);
        progress_bar = (ProgressBar) findViewById(R.id.progress_bar);
        listView1.setAdapter(mPairedDevicesAdapter);
        listView1.setOnItemClickListener(this);

        tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText("蓝牙电子秤测试");
        ButGetWeight = (Button) findViewById(R.id.ButGetWeight1);
        ButGetWeight.setOnClickListener(this);

    }

    /**
     * 广播监听器：负责接收搜索到蓝牙的广播
     */
    private BroadcastReceiver mDeviceFoundReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                /////更新UI
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String name = device.getName();
                String address = device.getAddress();
                if (devices == null) {
                    devices = new ArrayList<>();
                }
                //刷新设备显示列表
                BTDevice myDevice = new BTDevice();
                myDevice.setName(name);
                myDevice.setAddress(address);
                devices.add(myDevice);
                mPairedDevicesAdapter.add(name + "\n" + address);
                mPairedDevicesAdapter.notifyDataSetChanged();
            }
        }
    };

    /**
     * 开始扫描蓝牙设备
     */
    private void startDiscoveryDevice() {
        mPairedDevicesAdapter.notifyDataSetChanged();
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        mBluetoothAdapter.startDiscovery();
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        //退出应用时反注册设备监听器
        unregisterReceiver(mDeviceFoundReceiver);
        if(IControl !=null){
            IControl.bleDisconnect();
        }
    }

    @Override
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.ButTest) { //初始化按键
            progress_bar.setVisibility(View.VISIBLE);
            WeightData weightData = new WeightData();
            weightData.setAddress(Address);
            IControl = NewWeight.getInstance().NewControl(NewWeight.WEIGHTBLUETOOTH, this, this, weightData);
            IControl.bleConnect();
        } else if (i == R.id.ButGetWeight1) {  //获取重量按键
            if (IControl != null) {
                IControl.getWeight();
            } else {
                Toast.makeText(this, "请先初始化！", Toast.LENGTH_SHORT).show();
            }
        } else if (i == R.id.ButBreak) {  //断开按键
            //断开连接
            if (IControl != null) {
                IControl.bleDisconnect();
                mTvWeight.setText("____ kg");
            } else {
                Toast.makeText(this, "请先初始化！", Toast.LENGTH_SHORT).show();
            }
        } else if (i == R.id.rela_back) { //返回按键
            finish();
        } else if (i == R.id.ButComfirm) { //确认按键
            if (IControl != null) {
                //保存address
                SaveData();
                finish();
            } else {
                Toast.makeText(this, "请先初始化！", Toast.LENGTH_SHORT).show();
            }

        }
    }

    //回调address数据
    public void SaveData() {
        Intent intent = this.getIntent();
        intent.putExtra("mAddressSave", Address);
        this.setResult(-1, intent);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        try {
            if (devices != null || devices.size() != 0) {
                textTitle.setText(devices.get(i).getName());
                Address = devices.get(i).getAddress();
                BTName = devices.get(i).getName();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConnect(final String str, boolean is) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(BleConnectActivity.this, str, Toast.LENGTH_SHORT).show();
                progress_bar.setVisibility(View.GONE);
            }
        });
    }

    @Override
    public void onDisconnect(String str,boolean is) {
    }

    @Override
    public void onGetWeight(final String String, final boolean isSta) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (isSta) {
                    mTvWeight.setText("稳定：" + String + "kg");
                } else {
                    mTvWeight.setText("未稳定：" + String + "kg");
                }
            }
        });
    }


    class UserAdapter extends ArrayAdapter<String> {
        private int mResourceId;

        public UserAdapter(Context context, int textViewResourceId) {
            super(context, textViewResourceId);
            this.mResourceId = textViewResourceId;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            String str = getItem(position);
            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(mResourceId, null);
            TextView nameText = (TextView) view.findViewById(R.id.weight_tv_name);
            nameText.setText(str);
            return view;
        }
    }

    /**
     * 判断定位权限是否开启
     *
     * @param context
     * @return
     */
    public static boolean isLocationPermissionEnabled(Context context) {
        int permissionResult = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION);
        return permissionResult == PackageManager.PERMISSION_GRANTED;
    }
    public final static int REQUEST_LOCATION_PERMISSION_CODE = 0x03;
    public static void requestLocationPermission(AppCompatActivity activity) {
        ActivityCompat.requestPermissions(activity,
                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_LOCATION_PERMISSION_CODE);
    }

    public static void registerDeviceFoundReceiver(BroadcastReceiver receiver, AppCompatActivity activity) {
        IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        activity.registerReceiver(receiver, intentFilter);
    }

}
